package com.reform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.reform.config.JwtTokenUtil;
import com.reform.mapper.BatchPhaseMapper;
import com.reform.pojo.phase.BatchPhase;
import com.reform.pojo.project.PhaseTime;
import com.reform.mapper.PhaseTimeMapper;
import com.reform.pojo.phase.SimplifyBatch;
import com.reform.pojo.project.PostProject;
import com.reform.pojo.project.SimplifyProject;
import com.reform.res.Result;
import com.reform.res.ResultCode;
import com.reform.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reform.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.text.DateFormat;
import java.util.*;

/**
 * <p>
 * 阶段时间表 服务实现类
 * </p>
 *
 * @author mortale
 * @since 2021-07-15
 */
@Service
public class PhaseTimeServiceImpl extends ServiceImpl<PhaseTimeMapper, PhaseTime> implements IPhaseTimeService {

    @Autowired
    PhaseTimeMapper phaseTimeMapper;
    @Autowired
    BatchPhaseMapper batchPhaseMapper;
    @Autowired
    IViewProjectService viewProjectService;
    @Autowired
    IProjectService projectService;
    @Autowired
    IViewBatchService viewBatchService;

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    private static final String TEACHER = "phase_teacher";               //教师
    private static final String EXPERT = "phase_expert";                //专家
    private static final String SCHOOL_ADMIN = "phase_school";          //校管理员
    private static final String DEPARTMENT_ADMIN = "phase_department";         //院管理员

    @Override
    public Integer creatPhaseTime(PhaseTime phaseTime) throws SQLException {
        return phaseTimeMapper.insert(phaseTime);
    }

    @Override
    public Integer updatePhaseTime(PhaseTime phaseTime) throws SQLException {
        return phaseTimeMapper.updateById(phaseTime);
    }

    @Override
    public Integer deletePhaseTime(String batch_id) throws SQLException {
        Map<String, Object> map = new HashMap<>();
        map.put("batch_id", batch_id);
        return phaseTimeMapper.deleteByMap(map);
    }

    @Override
    public Result creatBatchPhase(PhaseTime phaseTime) {
        String uuid = UUIDUtils.getUUID();

        phaseTime.setBatchId("");
        phaseTime.setPhaseId(uuid);

        if (phaseTimeMapper.insert(phaseTime) < 0) {
            return Result.failure(ResultCode.FAILURE);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("phaseId", uuid);
        return Result.success(ResultCode.SUCCESS, map);
    }

    @Override
    public Result getPhaseById(String phaseId) {
        PhaseTime phaseTime = phaseTimeMapper.selectById(phaseId);
        List<BatchPhase> batchPhaseList = batchPhaseMapper.selectList(new QueryWrapper<BatchPhase>().eq("phase_id", phaseId));
        Map<String, Object> map = new HashMap<>();
        map.put("phase", phaseTime);
        map.put("selectInfo", batchPhaseList);
        return Result.success(ResultCode.SUCCESS, map);
    }

    @Override
    public Result updatePhase(PhaseTime phaseTime) {
        phaseTimeMapper.updateById(phaseTime);
        return Result.success(ResultCode.SUCCESS);
    }

    @Override
    public Result deletePhaseById(String phaseId) {
        int resPhaseTime = phaseTimeMapper.deleteById(phaseId);
        int resBatchPhase = batchPhaseMapper.delete(new QueryWrapper<BatchPhase>().eq("phase_id", phaseId));
        if (resBatchPhase > 0 || resPhaseTime > 0)
            return Result.success(ResultCode.SUCCESS);
        return Result.failure(ResultCode.FAILURE);
    }

    @Override
    public Result getAllPhase() {
        return Result.success(ResultCode.SUCCESS, phaseTimeMapper.selectList(new QueryWrapper<PhaseTime>().ne("type", 1)));
    }

    @Override
    public Result getNeedDealtPhase(HttpServletRequest request, Integer type) throws SQLException {

        String token = request.getHeader("token");
        if (token == null) {
            return Result.failure(ResultCode.USER_AUTH_Login_LAPSE);
        }
        String gh = jwtTokenUtil.getGHFromToken(token);

        List<SimplifyBatch> needDealtPhase1 = null;
        List<SimplifyBatch> needDealtPhase2 = null;
        List<SimplifyBatch> needDealtPhase3 = null;

        Map<String, Object> map = new HashMap<>();
        // 获取当前时间（yyyy/mm/dd）
        DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.CHINA);
        String date = df.format(new Date());

        //判断身份信息
        switch (type) {
            case 1:
                //教师
                //根据gh获取教师简单信息 项目编号、项目名称、批次结束时间
                List<SimplifyProject> projectList1 = projectService.getInitiationInfo(gh, 0);
                List<SimplifyProject> projectList2 = projectService.getInitiationInfo(gh, 5);
                map.put("initiation", projectList1);
                map.put("return", projectList2);
                return Result.success(ResultCode.SUCCESS, map);
            case 2:
                //类型(1 =>立项  2 => 中期   3=>结项)
                needDealtPhase1 = phaseTimeMapper.getTeacher(date, 1);
                needDealtPhase2 = phaseTimeMapper.getTeacher(date, 2);
                needDealtPhase3 = phaseTimeMapper.getTeacher(date, 3);
                //专家
                break;
            case 3:
                //校管理员
                //类型(1 =>立项  2 => 中期   3=>结项)
                needDealtPhase1 = phaseTimeMapper.getSchoolAdminFirst(date, 1);
                needDealtPhase2 = phaseTimeMapper.getSchoolAdminFirst(date, 2);
                needDealtPhase3 = phaseTimeMapper.getSchoolAdminFirst(date, 3);
                break;
            case 4:
                //院管理员
                //类型(1 =>立项  2 => 中期   3=>结项)
                needDealtPhase1 = phaseTimeMapper.getDepartmentAdmin(date, 1);
                needDealtPhase2 = phaseTimeMapper.getDepartmentAdmin(date, 2);
                needDealtPhase3 = phaseTimeMapper.getDepartmentAdmin(date, 3);
                break;
            default:
                //参数缺省
                return Result.failure(ResultCode.PARAM_IS_MISSING);
        }

        //如果是批次，项目在project中找
        for (SimplifyBatch simplifyBatch : needDealtPhase1) {
            List<String> proIdList = viewProjectService.getProIdByBatchId(simplifyBatch.getPhaseId());
            simplifyBatch.setCount(proIdList.size());
            simplifyBatch.setProIdLIst(proIdList);
        }
        map.put("batchId", needDealtPhase1);
        //否着是阶段，则在去phase_batch中找
        for (SimplifyBatch simplifyBatch : needDealtPhase2) {
            //先找属于该阶段下的批次信息
            List<String> batchIdList = viewBatchService.getBatchIdByPhaseId(simplifyBatch.getPhaseId());

            //筛选信息，查看该批次是否在审核时间内的批次
            int count = 0;
            List<String> resList = new ArrayList<>();
            for (String s : batchIdList) {
                if (phaseTimeMapper.getBatchIdByPhaseId(date, s) != null) {
                    //说明该批次在审核时间内
                    resList.add(s);
                }
            }
            simplifyBatch.setCount(count);
            simplifyBatch.setProIdLIst(resList);
        }
        map.put("phaseId", needDealtPhase2);
        //否着是阶段，则在去phase_batch中找
        for (SimplifyBatch simplifyBatch : needDealtPhase3) {
            //先找属于该阶段下的批次信息
            List<String> batchIdList = viewBatchService.getBatchIdByPhaseId(simplifyBatch.getPhaseId());
            //筛选信息，查看该批次是否在审核时间内的批次
            int count = 0;
            List<String> resList = new ArrayList<>();
            for (String s : batchIdList) {
                if (phaseTimeMapper.getBatchIdByPhaseId(date, s) != null) {
                    //说明该批次在审核时间内
                    resList.add(s);
                }
            }
            simplifyBatch.setCount(count);
            simplifyBatch.setProIdLIst(resList);
        }
        map.put("closeId", needDealtPhase3);
        return Result.success(ResultCode.SUCCESS, map);
    }

    @Override
    public Result updateBatchStatusById(String batchId, Integer status) {
        if (phaseTimeMapper.updateBatchStatusById(batchId, status) > 0)
            return Result.success(ResultCode.SUCCESS);
        return Result.failure(ResultCode.FAILURE);
    }

    @Override
    public List<String> getPhaseIdByType(int type) {
        return phaseTimeMapper.getPhaseIdByType(type);
    }


    @Override
    public Result getNeedDealt(String gh, Integer type) throws SQLException {

        List<SimplifyBatch> needDealtPhase1;
        List<SimplifyBatch> needDealtPhase2 = null;
        List<SimplifyBatch> needDealtPhase3;
        List<PostProject> needDealtPostProject = null;

        Map<String, Object> map = new HashMap<>();
        // 获取当前时间（yyyy/mm/dd）
        DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.CHINA);
        String date = df.format(new Date());

        //判断身份信息
        switch (type) {
            case 1:
                //教师
                //根据gh获取教师简单信息 项目编号、项目名称、批次结束时间
                List<SimplifyProject> projectList1 = projectService.getInitiationInfo(gh, 0);
                List<SimplifyProject> projectList2 = projectService.getInitiationInfo(gh, 5);
                map.put("initiation", projectList1);
                map.put("return", projectList2);
                return Result.success(ResultCode.SUCCESS, map);
            case 2:
                //类型(1 =>立项  2 => 中期   3=>结项)
                needDealtPhase1 = phaseTimeMapper.getExpert(date, 1, gh);
                needDealtPhase3 = phaseTimeMapper.getExpert(date, 3, gh);
                //专家
                break;
            case 3:
                //校管理员

                //类型(1 =>立项  2 => 中期   3=>结项)
                needDealtPhase1 = phaseTimeMapper.getSchoolAdminFirst(date, 1);
                needDealtPhase2 = phaseTimeMapper.getSchoolAdminFirst(date, 2);
                needDealtPhase3 = phaseTimeMapper.getSchoolAdminFirst(date, 3);
                needDealtPhase1.addAll(phaseTimeMapper.getSchoolAdminSecond(date, 1));
                needDealtPhase2.addAll(phaseTimeMapper.getSchoolAdminSecond(date, 2));
                needDealtPhase3.addAll(phaseTimeMapper.getSchoolAdminSecond(date, 3));
                needDealtPostProject = phaseTimeMapper.getDealtProject(25);
                map.put("admin", 1);
                break;
            case 4:
                //院管理员
                //类型(1 =>立项  2 => 中期   3=>结项)
                needDealtPhase1 = phaseTimeMapper.getDepartmentAdmin(date, 1);
                needDealtPhase2 = phaseTimeMapper.getDepartmentAdmin(date, 2);
                needDealtPhase3 = phaseTimeMapper.getDepartmentAdmin(date, 3);
                needDealtPostProject = phaseTimeMapper.getDealtProject(24);
                map.put("admin", 0);
                break;
            default:
                //参数缺省
                return Result.failure(ResultCode.PARAM_IS_MISSING);
        }

        //如果是批次，项目在project中找
        for (SimplifyBatch simplifyBatch : needDealtPhase1) {
            List<String> proIdList = viewProjectService.getProIdByBatchId(simplifyBatch.getPhaseId());
            simplifyBatch.setCount(proIdList.size());
            simplifyBatch.setProIdLIst(proIdList);
        }
        map.put("batchId", needDealtPhase1);

        //专家没有阶段
        if (type != 2) {
            //否着是阶段，则在去phase_batch中找
            for (SimplifyBatch simplifyBatch : needDealtPhase2) {
                //先找属于该阶段下的批次信息
                List<String> batchIdList = viewBatchService.getBatchIdByPhaseId(simplifyBatch.getPhaseId());

                //筛选信息，查看该批次是否在审核时间内的批次
                int count = 0;
                List<String> resList = new ArrayList<>();
                for (String s : batchIdList) {
                    if (phaseTimeMapper.getBatchIdByPhaseId(date, s) != null) {
                        //说明该批次在审核时间内
                        resList.add(s);
                    }
                }
                simplifyBatch.setCount(count);
                simplifyBatch.setProIdLIst(resList);
            }
            map.put("phaseId", needDealtPhase2);
        }

        //否着是阶段，则在去phase_batch中找
        for (SimplifyBatch simplifyBatch : needDealtPhase3) {
            //先找属于该阶段下的批次信息
            List<String> batchIdList = viewBatchService.getBatchIdByPhaseId(simplifyBatch.getPhaseId());
            //筛选信息，查看该批次是否在审核时间内的批次
            int count = 0;
            List<String> resList = new ArrayList<>();
            for (String s : batchIdList) {
                if (phaseTimeMapper.getBatchIdByPhaseId(date, s) != null) {
                    //说明该批次在审核时间内
                    resList.add(s);
                }
            }
            simplifyBatch.setCount(count);
            simplifyBatch.setProIdLIst(resList);
        }
        map.put("closeId", needDealtPhase3);
        map.put("needDealtPostProject", needDealtPostProject);
        return Result.success(ResultCode.SUCCESS, map);
    }

    @Override
    public Result updateScore(String batchId, String scorePath, String scorePathName) {
        int i = phaseTimeMapper.updateScore(batchId, scorePath, scorePathName);
        if (i > 0) {
            return Result.success(ResultCode.SUCCESS);
        }
        return Result.failure(ResultCode.FAILURE);
    }

    @Override
    public String getPhaseIdByStatus(String phaseId, int status) {
        return phaseTimeMapper.getPhaseIdByStatus(phaseId, status);
    }
}
